<script>
import {getUser} from "../../utils/utils";
import {getBabies} from "./api/babyutils";

export default {
  name: "BabyPhotos",
  props: {
    path: {  // 传入的地址
      type: String,
      default: "",
    },
    lastTime: {  // 传入的上次播放位置
      type: Number,
      default: 0,
    },
  },
  data(){
    return{
      babyId:'',
      fileList:[],
      babies:[],
      user:'',
      file:{},
      fileCover:{},
      video_photo:true,
      showPagination:false,
      pageSize:40,
      pageNum:1,
      totalSize:0,
      search_info:'',
      photos:[],
      showData:[],
      playedTime: this.lastTime,
      currentTime: 0,
      maxTime: 0,
      playOptions: {
        currentTime:0,
        height: "200px",
        width: "100%",
        playbackRates: [1.0], // 可选的播放速度
        autoplay: true, // 如果为true,浏览器准备好时开始回放
        muted: false, // 默认情况下静音播放
        loop: false, // 是否视频一结束就重新开始
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据，auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值，值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小，换句话说，它将按比例缩放以适应其容器
        sources: [
          {
            type: "video/mp4", // 类型
            src: "", // url地址，在使用本地的资源时，需要用require()引入，否则控制台会报错
          },
        ],
        poster: "./gcy-logo-200.png", // 设置封面地址
        notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息
        controlBar: {
          currentTimeDisplay: true,
          progressControl: true,  // 是否显示进度条
          playbackRateMenuButton: true, // 是否显示调整播放倍速按钮
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: true, // 是否显示剩余时间功能
          fullscreenToggle: true, // 是否显示全屏按钮
        },
      },
      dialogVisible:false,
      dialogVisible1:false,
      dialogFormVisible:false,
      form:{},
      showPhotoPath:'',
      showVideoPath:'',
      showTitle:'',
    }
  },
  methods:{
    handleChange1(file){
/*      let fd=new FormData
      fd.append('photo',file.raw)
      this.$axios.post('/auditing/photo',fd).then(resp=>{
        console.log(resp.data)
      })*/
      this.fileList.push(file)
    },
    handleRemove1(file, fileList){
      this.fileList=fileList
    },
    handleChange(file){
      this.fileCover=file
    },
    handleChangefile(file){
      this.file=file
    },
    handleRemove(file){
      this.file={}
    },
    uploadMyFile(){
      if (!this.form.babyId){
        this.$message.warning('请选择宝宝')
        return
      }
      if (!this.form.describe){
        this.$message.warning('请输入文件描述')
        return
      }
      if (this.video_photo){
        if (this.fileList.length===0) {
          this.$alert('请上传图片')
          return
        }
        let fd=new FormData
        Object.keys(this.form).forEach(key=>{
          fd.append(key, this.form[key])
        })
        this.fileList.forEach(file => {
          fd.append('photo', file.raw)
        })
        fd.append('userId',this.user.id)
        this.$axios.post('babyPic/uploadPhotos',fd).then(resp=>{
          alert(resp.data)
          this.getPhotosByBabyId(this.user.id)
          this.cleanData()
        })
      }else {
        if (!this.fileCover.raw){
          this.$message.warning('请选择视频封面')
          return;
        }
        if (!this.file.raw){
          this.$message.warning('请选择视频')
          return;
        }
        if (!(this.file.name.split('.').pop().toLowerCase()==='mp4')){
          this.$message.warning('请选择MP4格式的文件')
          return;
        }
        const fd=new FormData
        Object.keys(this.form).forEach(key=>{
          fd.append(key, this.form[key])
        })
        fd.append('fileCover',this.fileCover.raw)
        fd.append('file',this.file.raw)
        fd.append('userId',this.user.id)
        this.$axios.post("babyPic/uploadVideo",fd).then(resp=>{
          alert(resp.data)
          this.getPhotosByBabyId(this.user.id)
          this.cleanData()
        })
      }
    },
    cleanData(){
      this.form={}
      this.fileList=[]
      this.file={}
      this.fileCover={}
      this.dialogFormVisible=false
    },
    changeBaby(babyId){
      if(babyId!==0){
        this.form.babyId=babyId
      }
      this.babyId=babyId
      if(babyId===0){
        this.showData=this.photos
      }else {
        const new_show_data=[]
        for(let i=0; i<this.photos.length; i++){
          const item=this.photos[i]
          if (item.babyId===babyId){
            new_show_data.push(item)
          }
        }
        this.showData=new_show_data
      }
    },
    handleSizeChange(pageSize){
      this.pageSize=pageSize
      this.getPhotosByBabyId(this.user.id)
    },
    handleCurrentChange(pageNum){
      this.pageNum=pageNum
      this.getPhotosByBabyId(this.user.id)
    },
    // 准备好了
    onPlayerReady() {
      console.log("准备好了");
    },
    // 视频播放
    onPlayerPlay(player) {
      console.log('播放了');
      console.log(player);
      let playTime = 0;
      if (
        Number(Math.floor(this.playedTime)) ===
        Number(Math.floor(player.duration()))
      ) {
        this.playedTime = 0;
        playTime = 0;
      } else if (
        Number(Math.floor(player.currentTime())) !==
        Number(Math.floor(this.playedTime))
      ) {
        playTime = this.playedTime;
        player.currentTime(playTime)
      }
    },
    // 视频暂停的
    onPlayerPause(player) {
      console.log('暂停中');
      console.log(player);
      this.playedTime = player.currentTime();
    },
    // 视频播放完
    onPlayerEnd(player) {
      console.log('播放结束了');
      console.log(player);
    },
    // DOM元素上的readyState更改导致播放停止
    onPlayerWaiting(player) {
      console.log("播放停止中");
      console.log(player);
    },
    // 视频已开始播放
    onPlayerPlaying(player) {
      console.log("开始播放了");
      console.log(player);
    },
    // 当播放器在当前播放位置下载数据时触发
    onPlayerLoadeddata(player) {
      console.log("开始下载数据");
      console.log(player);
    },
    // 当前播放位置发生变化时触发
    onPlayerTimeupdate(player) {
      console.log("播放位置变化了");
      console.log(player);
      let timeDisplay = player.currentTime();
      if (timeDisplay - this.currentTime > 1) {
        player.currentTime(this.currentTime > this.maxTime ? this.currentTime : this.maxTime);
      }
      this.currentTime = player.currentTime();
      this.maxTime = this.currentTime > this.maxTime ? this.currentTime : this.maxTime;
    },
    //播放状态改变
    playerStateChanged(playerCurrentState) {
      console.log("播放状态变化了");
      console.log(playerCurrentState);
    },
    // 手动暂停视频的播放
    pause() {
      // 视频播放器的方法调用，要使用this.$refs.videoPlayer.player这个对象去调用
      this.$refs.videoPlayer.player.pause()
    },
    search_photo(){
      this.getPhotosByBabyId(this.user.id)
    },
    openInfo(item){
      if (item.sign===0){
        this.showTitle=item.describe
        this.showPhotoPath=item.photoPath
        this.dialogVisible=true
      }else {
        this.showTitle=item.describe
        const photo={type:'video/mp4',src:item.photoPath}
        this.playOptions.sources.push(photo)
        this.dialogVisible1=true
      }
    },
    handleClose(){
      this.showTitle=''
      this.dialogVisible=false
      this.dialogVisible1=false
      this.showPhotoPath=''
    },
    handleClose1(){
      this.showTitle=''
      this.dialogVisible1=false
      this.playOptions.sources.length=0
    },
    getPhotos(userId){
      this.$axios.get("babyPic/getPics?userId="+userId).then(resp=>{
        this.photos=resp.data.picVos
        this.showData=this.photos
        this.totalSize=resp.data.totalSize
        if(this.totalSize<40){
          this.showPagination=true
        }
      })
    },
    getPhotosByBabyId(userId){
      this.$axios.get(
        "babyPic/getPics?userId=" +userId+
        "&disc="+this.search_info+
        "&pageSize="+this.pageSize+
        "&pageNum="+this.pageNum
      ).then(resp=>{
        this.showData=resp.data.picVos
        this.totalSize=resp.data.totalSize
        if(this.totalSize<40){
          this.showPagination=true
        }
      })
    },
    uploadFile(){
      this.dialogFormVisible=true
    },
    /**
     * @desc 监听回车键执行事件
     **/
    keyDown(e) {
      // 回车则执行登录方法 enter键的ASCII是13
      if (e.keyCode === 13) {
        this.search_photo()
      }
    },
  },
  created() {
    this.user=getUser()
    this.getPhotos(this.user.id)
    this.$axios.get('babyPic/getBabies?userId=' + this.user.id).then(resp=>{
      this.babies=resp.data
    })
  },
  /**
   * @desc 绑定监听事件
   **/
  mounted() {
    window.addEventListener('keydown', this.keyDown)
  },

  /**
   * @desc 销毁事件
   **/
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false)
  },
}
</script>

<template>
<div>
  <div style="width: 350px;display: inline-block;">
    <!-- 搜索 -->
    <el-input
      v-model="search_info"
      placeholder="请输入照片描述"
      prefix-icon="el-icon-search"
      style="width: 300px"
    ></el-input>
    <el-button icon="el-icon-search" circle @click="search_photo"></el-button>
  </div>
  <div style="width: 350px;display: inline-block;margin-left: 40px">
    <el-button type="primary" @click="uploadFile">上传照片</el-button>
  </div>
  <div style="width: 350px;display: inline-block;margin-left: 40px">
    <el-pagination
      :hide-on-single-page="showPagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[40, 60, 80, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalSize">
    </el-pagination>
  </div>
  <!-- 宝宝的照片 -->
  <div class="waterfall" style="
  margin-top: 10px;
  padding-left: 10px;
  column-count: 6;
  column-gap: 0;
  margin-bottom: 150px;">
    <div class="watch_item"
         style="
                break-inside: avoid;
                width: 175px;
                margin-bottom: 12px;
                border-radius: 5px;
                padding-bottom: 5px;"
         v-for="item in showData" :key="item.id"
    >
      <img :src="item.coverPath" alt="" srcset="" style="border-radius: 10px;" width="175px" height="auto" @click="openInfo(item)">
<!--      <video-player
        width="175px"
        height="auto"
        :options="playOptions"
        v-if="item.sign===1"
        :src="item.cover"
         poster="http://192.168.138.131:9000/picture/headPhoto.png"
      />-->
      <div class="watch_item_middle" style="padding: 5px;"><span v-html="item.title"></span></div>

      <div class="watch_item_bottom"
          style="padding: 15px;
          height: 25px;
          line-height: 12px;
          text-align: center;
          font-weight: 500;
          font-size: 27px;
          color: #333;
          display: flex;
          justify-content: space-around;">
        <div>
          <span class="name" style="
          /*padding-left: 10px;*/
          color: #666666;
          font-weight: 500;
          font-size: 14px;" v-html="item.describe"></span>
          <el-tag size="mini" v-show="item.sign===0">图片</el-tag>
          <el-tag size="mini" v-show="item.sign===1">视频</el-tag>
        </div>
      </div>
    </div>
  </div>
  <el-dialog
    title="详情"
    :visible.sync="dialogVisible"
    width="50%">
    <p v-html="showTitle" style="font-size: large"></p>
    <img :src="showPhotoPath" alt="图片详情" width="100%">
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleClose">确 定</el-button>
    </span>
  </el-dialog>
  <el-dialog
    :title="showTitle"
    :visible.sync="dialogVisible1"
    :before-close="handleClose1"
    width="50%">
<!--    <video-player
      width="175px"
      height="auto"
      :options="playOptions"
      :src="showVideoPath"
    />-->
    <video-player
      ref="videoPlayer"
      class="player-video"
      :playsinline="false"
      :options="playOptions"
      @ready="onPlayerReady"
      @play="onPlayerPlay($event)"
      @pause="onPlayerPause($event)"
      @ended="onPlayerEnd($event)"
      @waiting="onPlayerWaiting($event)"
      @playing="onPlayerPlaying($event)"
      @loadeddata="onPlayerLoadeddata($event)"
      @timeupdate="onPlayerTimeupdate($event)"
      @statechanged="playerStateChanged($event)"
    />
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose1">取 消</el-button>
      <el-button type="primary" @click="handleClose1">确 定</el-button>
    </span>
  </el-dialog>
  <el-dialog title="上传" :visible.sync="dialogFormVisible" :before-close="cleanData">
    <div style="width: 120px">
      <el-switch
        style="display: block"
        v-model="video_photo"
        active-color="#13ce66"
        inactive-color="#ff4949"
        active-text="图片"
        inactive-text="视频"
      >
      </el-switch>
    </div>
    <br>
    <el-form :model="form">
      <el-form-item label="选择宝宝">
        <el-select v-model="form.babyId" placeholder="请选择宝宝">
          <el-option
            v-for="baby in babies"
            :key="baby.id"
            :label="baby.name"
            :value="baby.id">
            <span style="float: left">{{ baby.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ baby.petName }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="输入文件描述">
        <el-input
          type="textarea"
          autosize
          placeholder="请输入内容"
          v-model="form.describe">
        </el-input>
      </el-form-item>
      <el-upload
        class="upload-demo"
        action=""
        :auto-upload="false"
        :on-change="handleChange1"
        :on-remove="handleRemove1"
        multiple
        :limit="9"
        list-type="picture-card"
        :file-list="fileList"
        v-if="video_photo"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
      <el-upload
        class="upload-demo"
        action=""
        :auto-upload="false"
        list-type="picture"
        :limit="1"
        :on-change="handleChange"
        v-if="video_photo===false"
      >
        <el-button size="small" type="primary">上传封面</el-button>
      </el-upload>
      <br>
      <el-upload
        class="upload-demo"
        action=""
        :auto-upload="false"
        :on-remove="handleRemove"
        :on-change="handleChangefile"
        :limit="1"
        drag
        v-if="video_photo===false">
        <i class="el-icon-upload"></i>
        <p>上传视频</p>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传mp4文件，且不超过2GB</div>
      </el-upload>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cleanData">取 消</el-button>
      <el-button type="primary" @click="uploadMyFile">确 定</el-button>
    </div>
  </el-dialog>
</div>
</template>

<style scoped>

/*
.watch_item {
  border: 2px solid black;
  break-inside: avoid; //避免“瀑布流”内部的内容被断开
  width: 175px;
  margin-bottom: 12px;
  border-radius: 5px;
  padding-bottom: 5px;
  img {
    //border-radius: 10px;
  }
  .watch_item_middle {
    padding: 5px;
  }
  .watch_item_bottom {
    padding: 5px;
    height: 25px;
    line-height: 25px;
    text-align: center;
    font-weight: 500;
    font-size: 14px;
    color: #333;
    display: flex;
    justify-content: space-around;
    .name {
      padding-left: 10px;
      color: #666666;
      font-size: 12px;
    }
    .zan {
      padding-left: 10px;
    }
  }
}
*/

.watch_item:hover {
  cursor: pointer;
  transform: scale(1.02);
  transition-duration:0.1s;
  transition-timing-function:linear;
  transition-delay:0s;
  transition-property:all;
  box-shadow:5px 5px 20px 5px rgba(16, 28, 5, 0.5);
  // 对比度变为之前的1.35倍
  filter: contrast(1.45);
  background-color: rgb(255, 255, 255,0.5);
}
</style>
